#include "main.h"
#define TIMEOUT 1000000 // 1000ms


int socket_init(uint8_t *addr, uint16_t port){
	int fd = socket(AF_INET, SOCK_DGRAM, 0);
	if(fd < 0){
		perror("socket");
		exit(-1);
	}

	//reuse port
	int opt = 1;
    if(setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) < 0){
		perror("setsockopt");
		exit(-1);
	}

	//set none block
	/*
	opt = fcntl(fd, F_GETFD, 0);
	if(opt < 0 || fcntl(fd, F_SETFL, opt|O_NONBLOCK) < 0){
		perror("fcntl");
		exit(-1);
	}
	*/
	struct timeval tv;
	tv.tv_sec = (int)(TIMEOUT / 1000000);
	tv.tv_usec = (TIMEOUT % 1000000);
	if(setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)) < 0){
		perror("setsockopt");
		exit(-1);
	}

	//bind addr
	struct sockaddr_in sa;
	sa.sin_family = AF_INET;
	sa.sin_port = htons(port);
	sa.sin_addr.s_addr = inet_addr(addr);
	if(bind(fd, (struct sockaddr *)&sa, sizeof(sa)) < 0){
		perror("bind");
		exit(-1);
	}
	
	return fd;
}

int c_send(){

}

int c_recv(conn_t *conn, uint8_t *rbuf, size_t rlen){
	return recvfrom(conn->fd, rbuf, rlen, 0, conn->sa, conn->sa_len);
}

//return the clock as ms
long long int iclock(){
	struct timeval tv;
	gettimeofday(&tv, NULL);
	//printf("%ld,%ld\n", tv.tv_sec, tv.tv_usec);
	return tv.tv_sec*1000+tv.tv_usec/1000;
}
